<template>
  <base-breadcrumb :title="titleName">
    <searchData
      :search-data="searchArr"
      @search="search"
    />

    <a-card :bordered="false">
      <!-- <title-name title="大客户列表" /> -->

      <div class="table-operator">
        <a-button
          v-btnPermission="[{code:'seex_pm_003_add_01',ident:'prma_seex'},{code:'buco_pm_003_add_01',ident:'prma_buco'}]"
          type="primary"
          icon="plus"
          @click="handleAdd"
        >
          新增大客户
        </a-button>
        <a-button @click="handleDel"  v-btnPermission="[{code:'seex_pm_003_del_04',ident:'prma_seex'},{code:'buco_pm_003_del_04',ident:'prma_buco'}]">
          删除
        </a-button>
      </div>
      <!-- 统计汇总 -->
      <AuditSummary ref="auditSummary" title="大客户列表" style="margin-bottom: 12px" :countList="countList" />
      <list-table
        ref="table"
        size="default"
        :row-key="record=>record.customerId"
        :columns="columns"
        :request="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumpers
        :row-selection="rowSelection"
        :scoped-slots="$scopedSlots"
        show-pagination="auto"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <span
          slot="status"
          slot-scope="text"
        >
          <a-badge
            :status="text | statusTypeFilter"
            :text="text | statusFilter"
          />
        </span>
        <span
          slot="description"
          slot-scope="text"
        >
          <ellipsis
            :length="8"
            tooltip
          >{{ text }}</ellipsis>
        </span>
        <span
          slot="action"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
               v-btnPermission="[{code:'seex_pm_003_loo_02',ident:'prma_seex'},{code:'buco_pm_003_loo_02',ident:'prma_buco'}]"
              @click="handleSub(record)"
            >查看</a>
            <a
               v-btnPermission="[{code:'seex_pm_003_edi_03',ident:'prma_seex'},{code:'buco_pm_003_edi_03',ident:'prma_buco'}]"
              @click="handleEdit(record)"
            >编辑</a>
          </MoreButton>
        </span>
      </list-table>

      <add-customer
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />

      <find-customer
        :visible="visibles"
        :loading="confirmLoading"
        :model="mdls"
        @cancel="handleCancels"
      />
    </a-card>
  </base-breadcrumb>
</template>

<script>
  import moment from 'moment'
  import { STable, Ellipsis } from '@/components'
  import { getCustomerList, getCustomersOne, addCustomers, editCustomers, getCustomersLevel,delCustomers } from '@/api/project/customers'

  import addCustomer from './addCustomer'
  import findCustomer from './findCustomer'
  import AuditSummary from '@/views/quality/components/AuditSummary' // 统计汇总
  import ARow from 'ant-design-vue/es/grid/Row'

  const columns = [
    {
      title: '序号',
       width: 65,

      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '客户名称',
      width: 100,
      dataIndex: 'customerName'
    },
    {
      title: '客户层级',
      width: 100,
      dataIndex: 'customerHierarchy',
    },
    {
      title: '客户级别',
      width: 100,
      dataIndex: 'customerLevel',

    },
    {
      title: '状态',
      width: 100,
      dataIndex: 'customerStatus',
      scopedSlots: { customRender: 'customerStatus' }
    },
    {
      title: '操作',
      dataIndex: 'action',
     width: 180,
      scopedSlots: { customRender: 'action' }
    }
  ]

  const statusMap = {
    0: {
      status: 'default',
      text: '关闭'
    },
    1: {
      status: 'processing',
      text: '运行中'
    },
    2: {
      status: 'success',
      text: '已上线'
    },
    3: {
      status: 'error',
      text: '异常'
    }
  }

  export default {
    name:'a'+Date.now(),
    components: {
      addCustomer,
      STable,
      Ellipsis,
      findCustomer,
      AuditSummary
    },
    data() {
      this.columns = columns
      return {
        cacheSelecRows: [],
        searchArr: [
          // 搜索框
          {
            name: '客户名称',
            value: 'customerName',
            type: 'input'
          },
          {
            name: '客户层级',
            value: 'customerHierarchyCode',
            type: 'select',
            data:[

            ]
          },
          {
            name: '客户级别',
            value: 'customerStatusCode',
            type: 'select',
            data:[

            ]
          },
          {
            name:'状态',
            value:'typeStatusCode',
            type:'select',
            data:[
              {
                value: '',
                label: '全部'
              },
              {
                value: '1',
                label: '可用'
              },
              {
                value: '0',
                label: '不可用'
              }
            ],
          }
        ],
        datas:[],
        titleName:'',
        // create model
        visible: false,
        visibles: false,  // 查询大客户
        confirmLoading: false,
        mdl: null,
        mdls: null,
        isEdit:false,
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {

        },
        editData:{},

        loadData:parameter => {
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          return getCustomerList(requestParameters)
            .then(res => {
              // 更新汇总总数
              this.$nextTick(() => {
                this.$refs.auditSummary && this.$set(this.$refs.auditSummary.countInfo, 'total', res.totalSize)
              })
              return res
            })
        },
        selectedRowKeys: [],
        selectedRows: [],
        ids:[],
        countList: [
          {
            title: '总数：',
            value: 'total',
            needUnit: true
          },
          {
            key: 'select',
            title: '已选择',
            value: 0
          }
        ], // 汇总列表
      }
    },
    watch:{

    },
    filters: {
      statusFilter(type) {
        return statusMap[type].text
      },
      statusTypeFilter(type) {
        return statusMap[type].status
      }
    },
    created() {

      // this.getCustomerList();
      this.getCustomersLevel();


    },
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          selectedRows: this.selectedRows,   // 当前行所有数据
          onChange: this.onSelectChange
        }
      }
    },
    methods: {
      handleDel(){
        let that = this
        if(that.selectedRows.length == 0){
          that.$message.error('请先选择删除的大客户！')
          return
        }
        that.$confirm({
          title: '删除',
          content: '确定删除大客户吗？',
          onOk() {
            delCustomers({ids:that.ids}).then(res=>{
              if(res.data == 200 || res.data.code == 200){
                that.$message.success('删除成功！')
                that.$refs.table.refresh(true)
                that.selectedRows = []
                that.selectedRowKeys = []
              }
            })
          },
          onCancel() {},
        });

      },
      search(values){
        this.queryParam = values
        this.$refs.table.refresh(true)
      },
      getCustomersLevel(){
        getCustomersLevel().then(res=>{

          let arr1 = res.data.customerHierarchyList
          let arr2 = res.data.customerLevelList
          this.searchArr[1].data = this.getLabelData(arr1)
          this.searchArr[2].data = this.getLabelData(arr2)
        })
      },
      getCustomerList(){
        getCustomerList(this.queryParam).then(res => {
            this.datas = res.data
          })
      },
      resetSearch(){
        this.queryParam = {}
      },
      deletes(){},
      handleAdd() {
        this.mdl = {}
        this.visible = true
        this.isEdit = false
      },
      handleEdit(record) {
        this.visible = true
        this.mdl = { ...record }
        this.isEdit = true
      },
      handleOk() {
        let that = this;
        const form = that.$refs.createModal.form
        form.validateFields((errors, values) => {
          if (!errors) {
            if (that.isEdit == true) {
              // 修改
              that.mdl.customerName = values.customerName
              that.mdl.customerHierarchyCode = values.customerHierarchyCode
              that.mdl.customerLevelCode = values.customerLevelCode
              that.mdl.customerStatusCode = values.customerStatusCode
              that.confirmLoading = true
              editCustomers(that.mdl).then(res=>{
                that.confirmLoading = false
                if(res.data.code===200){
                  that.visible = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格

                  that.$refs.table.refresh(true)
                  that.$message.success('修改成功')
                }else{
                  that.$message.error('修改失败')
                }

              }).catch(()=>{
                that.confirmLoading = false
              })

            } else {
              // 新增
              that.confirmLoading = true
              addCustomers(values).then(res=>{
                that.confirmLoading = false
                if(res.code === 200){
                  that.visible = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格

                  that.$refs.table.refresh(true)
                  that.$message.success('新增成功')
                }else{
                  that.$message.success('新增失败')
                }
              }).catch(()=>{
                that.confirmLoading = false
              })
            }
          }
        })
      },
      handleCancel() {
        this.visible = false
        const form = this.$refs.createModal.form
        form.resetFields() // 清理表单数据（可不做）
      },
      handleCancels() {
        this.visibles = false
      },
      handleSub(record) {
        this.visibles = true
        this.mdls = { ...record }
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        const arr2 =  this.setTableListTopNum(this.cacheSelecRows, selectedRowKeys, selectedRows, 'customerId')
        this.cacheSelecRows = arr2;
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = arr2
        let arr = []
        this.cacheSelecRows.forEach(function(obj,i) {
          arr.push(obj.customerId)
        })
        this.ids = arr
        this.countList[1].value =  arr2.length
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      resetSearchForm() {
        this.queryParam = {
          date: moment(new Date())
        }
      }
    }
  }
</script>



